package szcg.framework.library.base.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import szcg.framework.library.base.PostServiceImpl;
import szcg.framework.library.base.entity.TokenBean;
import szcg.framework.library.base.service.TokenService;
import szcg.framework.library.utils.EncryptionUtils;

import java.util.HashMap;

@Service
public class TokenServiceImpl extends PostServiceImpl implements TokenService {

    private static final Logger logger = LoggerFactory.getLogger(TokenServiceImpl.class);

    private static final String secretKey = "1A0ErhOMJoZ0VHhbO6kLIDNyKC1aWG5K";

    @Qualifier("JedisPool")
    private final JedisPool jedisPool;

    public TokenServiceImpl(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Override
    public String generateToken(String userId) {
        long l = System.currentTimeMillis();
        TokenBean tokenBean = new TokenBean();
        tokenBean.tokenTime = String.valueOf(l);//发行时间
        tokenBean.userId = userId;//用户id
        String jsonString = JSON.toJSONString(tokenBean);
        String token = EncryptionUtils.encrypt(secretKey, jsonString);
        //保存至redis,默认有效期是8小时(单位：秒)
        long survivalTime = 60 * 60 * 8;
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.setex(userId, survivalTime, token);
        }
        return token;
    }

    @Override
    public HashMap<String, String> verifier(String realBody) {
        HashMap<String, String> resMap = new HashMap<>();
        if (realBody == null || realBody.isEmpty()) {
            resMap.put("state", "001");
            resMap.put("msg", "body为空");
            return resMap;
        }
        JSONObject jsonObject = (JSONObject) JSON.parse(realBody);
        String token = jsonObject.getString("token");
        if (token == null || token.isEmpty()) {
            resMap.put("state", "002");
            resMap.put("msg", "token为空");
            return resMap;
        }
        String tokenJson = EncryptionUtils.decrypt(secretKey, token);
        TokenBean tokenBean = JSONObject.parseObject(tokenJson, TokenBean.class);
        String userId = tokenBean.userId;
        if (userId == null || userId.isEmpty()) {
            resMap.put("state", "003");
            resMap.put("msg", "token解析失败");
            return resMap;
        }
        try (Jedis jedis = jedisPool.getResource()) {
            boolean exists = jedis.exists(userId);
            if (!exists) {
                //不存在，说明过期了
                resMap.put("state", "004");
                resMap.put("msg", "Token已过期,请重新登录");
                return resMap;
            }
            //判断redis中的token和参数token是否相等
            String latestToken = jedis.get(userId);
            if (latestToken == null || !latestToken.equals(token)) {
                //被其他设备登录了，不是最新的token
                resMap.put("state", "005");
                resMap.put("msg", "已在其他设备登陆，请从新登录");
                return resMap;
            }
            resMap.put("state", "000");
            resMap.put("msg", "验证通过");
            return resMap;
        }
    }
}
